<template>
  <DetailsFormBox :title="page.title" :type="route.query.type" :form="data.form" :btns="[
    {
      title: '重置',
      icon: '',
      type: '',
      hidden: !isEdit,
      click: getForm,
    },
    {
      title: '保存',
      icon: '',
      type: 'primary',
      hidden: !isEdit,
      click: (form: any) => {
        saveBtn(form, false)
      },
    },
  ]" :loading="data.loading" :loadingMsg="data.loadingMsg">
    <template #default="{ form }">
      <div class="p-12">
        <OrderInfo :produceTaskBillNo="route.query.produceTaskBillNo" @changeBtn="(row: any) => {
          data.productOrder = row
        }" />
        <CellBox title="基本信息" isTop>
          <FlexBox :margin="2">
            <ElFormItemBox label="作业编号" prop="workTaskNo">
              {{ form?.workTaskNo || '系统自动生成' }}
            </ElFormItemBox>
            <ElFormItemBox label="创建时间" prop="workBeginTime">
              {{ form?.workBeginTime || '系统自动生成' }}
            </ElFormItemBox>
            <ElFormItemBox label="创建人员" prop="workPersonName">
              {{ form?.workPersonName || '系统自动生成' }}
            </ElFormItemBox>
          </FlexBox>
        </CellBox>
        <CellBox title="作业内容" isTop>
          <FlexBox>
            <ElFormItemBox label="工艺名称">
              <ElInputBox :data="form" dataName="craftTaskName" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="机台名称">
              <ElInputBox :data="form" dataName="machineName" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="生产设备">
              <ElInputBox :data="form" dataName="equipmentName" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="设备类型">
              <ElInputBox :data="form" dataName="machineTypeName" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="作业状态" prop="craftWorkState" isRules>
              <ElSelectBox :data="form" dataName="craftWorkState" :options="options.craftWorkState" disabled
                @changeBtn="getWorkState(form)" />
            </ElFormItemBox>
            <template v-if="['检验', '模切'].includes(form.machineTypeName)">
              <ElFormItemBox :label="['检验'].includes(form.machineTypeName)
                ? '检验数量'
                : '模切刀次'" prop="cropCount" isRules>
                <ElInputBox :data="form" dataName="cropCount" :unit="['检验'].includes(form.machineTypeName)
                  ? data.productOrder?.baseData?.productUnion
                  : '次'" :disabled="!isEdit || !['检验', '模切'].includes(form.machineTypeName)"
                  @changeBtn="changeProduceMeters(form)" />
              </ElFormItemBox>
              <ElFormItemBox label="每版数量">
                <ElNumberBox :data="form" dataName="perGroupCount"
                  :disabled="!isEdit || !['检验'].includes(form.machineTypeName)"
                  @changeBtn="changeProduceMeters(form)" />
              </ElFormItemBox>
              <ElFormItemBox label="每版高度">
                <ElNumberBox :data="form" dataName="perGroupHeight" unit="mm"
                  :disabled="!isEdit || !['检验', '模切'].includes(form.machineTypeName)"
                  @changeBtn="changeProduceMeters(form)" />
              </ElFormItemBox>
              <!-- <ElFormItemBox label="每版跳距">
              <ElNumberBox :data="form" dataName="skipDistance" unit="mm" :disabled="!isEdit"
                @changeBtn="changeProduceMeters(form)" />
            </ElFormItemBox> -->
            </template>
            <ElFormItemBox label="生产米数" prop="produceMeters" isRules>
              <ElNumberBox :data="form" dataName="produceMeters" unit="米" :disabled="!isEdit" />
            </ElFormItemBox>
            <ElFormItemBox label="不良米数">
              <ElNumberBox :data="form" dataName="defectiveProductsMeters" unit="米" :disabled="!isEdit" />
            </ElFormItemBox>
            <ElFormItemBox label="不良率">
              <ElNumberBox :data="otherDefectiveRate(form)" unit="%" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="作业备注" :prop="`workTaskRemark`" class="wAuto">
              <ElInputBox :data="data" dataName="workTaskRemark" type="textarea" :disabled="!isEdit" />
            </ElFormItemBox>
          </FlexBox>
        </CellBox>
        <CellBox title="生产工时" isTop>
          <FlexBox>
            <ElFormItemBox label="总工时">
              <ElNumberBox :data="form" dataName="taskUseTime" unit="分钟" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="吃饭时间">
              <ElNumberBox :data="form" dataName="dinnertime" unit="分钟" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="实际工时">
              <ElNumberBox :data="actualWorkTime(form)" unit="分钟" disabled />
            </ElFormItemBox>
          </FlexBox>
        </CellBox>
        <CellBox title="作业用时明细" isTop>
          <template #btn>
            <ElTooltipBox data="生产忘记点完工，辅助快速完成">
              <el-link @click="() => {
                const _row = data.productOrder?.produceCraftList?.find((el: any) => el.produceCraft.craftTaskNo === form.craftTaskNo)
                if (_row) {
                  const _endTiem = _row.produceCraft.craftTaskPlanUseTime//计划用时
                  const _listMx = form.produceCraftWorkTaskFragments
                  const _listRow = _listMx[_listMx.length - 1]
                  if (_listRow.fragmentBeginTime && _endTiem) {
                    console.log(proxy.$addMinutesToTime(_listRow.fragmentBeginTime, 30));
                    _listRow.fragmentEndTime = proxy.$addMinutesToTime(_listRow.fragmentBeginTime, _endTiem)
                    _listRow.fragmentEndType = 2
                    _listRow.fragmentEndRemark = '忘记点完成'
                    form.craftWorkState = 1
                  } else {
                    proxy.$message('开始时间未选择或计划用时没设置', 'error');
                  }
                }
              }">快速完成作业</el-link>
            </ElTooltipBox>
          </template>
          <TableBoxMx :data="{
            disabled: !isEdit,
            tbody: form.produceCraftWorkTaskFragments,
            thead: [
              {
                label: '开始时间',
                prop: 'fragmentBeginTime',
                align: 'center',
                width: 220,
                formType: 'dayTime',
                formProp: `produceCraftWorkTaskFragments`,//必填
                changeBtn: (value: any, row: any, arr: any, rowIndex: number) => {
                  const _list = form.produceCraftWorkTaskFragments
                  const compareDates = proxy.$compareDates(row.fragmentBeginTime, row.fragmentEndTime)
                  if (compareDates === 1) {
                    row.fragmentBeginTime = ''
                    proxy.$message('开始时间不能晚于结束时间', 'error')
                  } else {
                    if (rowIndex !== 0) {
                      const compareDates2 = proxy.$compareDates(row.fragmentBeginTime, _list[rowIndex - 1].fragmentEndTime)
                      if ([0, -1].includes(compareDates2)) {
                        row.fragmentBeginTime = ''
                        proxy.$message('开始时间不能早于和等于上个片段的结束时间', 'error')
                      }
                    }
                  }
                }
              },
              {
                label: '结束时间',
                prop: 'fragmentEndTime',
                align: 'center',
                width: 220,
                formType: 'dayTime',
                formProp: `produceCraftWorkTaskFragments`,//必填
                isRules: (row: any) => {
                  return row.fragmentEndType === 0
                },
                disabled: (row: any, rowIndex: number) => {
                  return !!!row.fragmentBeginTime || row.fragmentEndType === -1
                },
                changeBtn: (value: any, row: any, arr: any, rowIndex: number) => {
                  const compareDates = proxy.$compareDates(row.fragmentBeginTime, row.fragmentEndTime)
                  const _list = form.produceCraftWorkTaskFragments
                  if (compareDates === 1) {
                    row.fragmentEndTime = ''
                    proxy.$message('结束时间不能早于开始时间', 'error')
                  } if (rowIndex !== _list.length - 1) {
                    const compareDates2 = proxy.$compareDates(row.fragmentEndTime, _list[rowIndex + 1].fragmentBeginTime)
                    if ([1].includes(compareDates2)) {
                      row.fragmentEndTime = ''
                      proxy.$message('结束时间不能晚于和等于下个片段的开始时间', 'error')
                    }
                  }
                }
              },
              {
                label: '作业耗时',
                prop: 'elapsedTime',
                align: 'center',
                width: 160,
              },
              {
                label: '结束方式',
                prop: 'fragmentEndType',
                align: 'center',
                width: 160,
                formType: 'select',
                formProp: `produceCraftWorkTaskFragments`,//必填
                disabled: (row: any, rowIndex: number) => {
                  return rowIndex !== form.produceCraftWorkTaskFragments.length - 1
                },
                options: [
                  {
                    label: '作业中',
                    value: -1,
                    disabled: (row: any, rowIndex: number) => {
                      return rowIndex !== form.produceCraftWorkTaskFragments.length - 1
                    },
                  },
                  {
                    label: '暂停',
                    value: 0,
                  },
                  {
                    label: '分批',
                    value: 1,
                    disabled: (row: any, rowIndex: number) => {
                      return rowIndex !== form.produceCraftWorkTaskFragments.length - 1
                    },
                  },
                  {
                    label: '完成',
                    value: 2,
                    disabled: (row: any, rowIndex: number) => {
                      return rowIndex !== form.produceCraftWorkTaskFragments.length - 1
                    },
                  },
                ],
                changeBtn: (value: any, row: any) => {
                  const _list = form.produceCraftWorkTaskFragments
                  const _lastRow = _list[_list.length - 1]
                  switch (_lastRow.fragmentEndType) {
                    case -1://作业中
                      row.fragmentEndTime = ''
                      row.fragmentEndReason = 0
                      form.craftWorkState = 0
                      break;
                    case 0://暂停
                      form.craftWorkState = 3
                      row.fragmentEndReason = 3
                      break;
                    case 1://分批
                    case 2://完成
                      form.craftWorkState = 1
                      break;
                  }
                }
              },
              {
                label: '结束原因',
                prop: 'fragmentEndReason',
                align: 'center',
                width: 160,
                formType: 'select',
                options: [
                  {
                    label: '未知',
                    value: -1,
                  },
                  {
                    label: '作业',
                    value: 0,
                  },
                  {
                    label: '调机',
                    value: 1,
                  },
                  {
                    label: '开会',
                    value: 2,
                  },
                  {
                    label: '其他',
                    value: 3,
                  },
                ]
              },
              {
                label: '结束备注',
                prop: 'fragmentEndRemark',
                align: 'left',
                width: null,
                formType: 'text'
              }
            ],
            operation: [
              {
                label: '删除',
                icon: 'Delete',
                hidden: (row: any, index: any) => {
                  return form.produceCraftWorkTaskFragments.length - 1 === index
                }
              }
            ],
            add: () => {
              const _list = form.produceCraftWorkTaskFragments
              const _lastRow = _list[_list.length - 1]
              switch (_lastRow.fragmentEndType) {
                case -1:
                  proxy.$message('当前作业在作业中，不可添加', 'error')
                  break;
                case 0:
                  _list.push({
                    fragmentBeginTime: '',//片段开始时间
                    fragmentEndTime: '',//片段结束时间
                    fragmentEndType: '',//片段结束方式：0-暂停、1-分批、2-完成	
                    fragmentEndReason: '',//片段结束原因：0-作业、1-调机、2-开会、3-其它
                    fragmentEndRemark: '',//片段结束备注
                  })
                  break;
                case 1:
                  proxy.$message('当前作业已分批，不可添加', 'error')
                  break;
                case 2:
                  proxy.$message('当前作业已完成，不可添加', 'error')
                  break;
                default:
                  proxy.$message('请先选择最后片段的结束方式', 'error')
                  break;
              }
            }
          }">
            <template #elapsedTime="{ row }">
              {{ `${proxy.$getMinutesDifference(row.fragmentBeginTime, row.fragmentEndTime)}分钟` }}
            </template>
          </TableBoxMx>
        </CellBox>
        <CellBox title="印刷记录表" isTop>
          <TableBoxMx :data="{
            disabled: true,
            tbody: form.wordList,
            thead: [
              {
                label: '卷号',
                prop: 'rollNo',
                align: 'center',
                width: 120,
              },
              {
                label: '打印页码起号',
                prop: 'printPageStart',
                align: 'center',
                width: 120,
              },
              {
                label: '打印页码止号',
                prop: 'printPageEnd',
                align: 'center',
                width: 120,
              },
              {
                label: '拼版枚数',
                prop: 'layoutCount',
                align: 'center',
                width: 120,
              },
              // {
              //   label: '报工人',
              //   prop: 'createPerson',
              //   align: 'center',
              //   width: 120,
              // },
              // {
              //   label: '报工时间',
              //   prop: 'createTime',
              //   align: 'center',
              //   width: 120,
              // },
              {
                label: '备注',
                prop: 'remark',
                align: 'left',
                width: null,
              },
            ],
          }">
          </TableBoxMx>
        </CellBox>
      </div>
    </template>
  </DetailsFormBox>
</template>
<script setup lang="ts">
import { sendMsg } from '@/utils/crossTagMag.ts';
import page from '../page.ts'; // 引入逻辑
import '../pageCss.scss'; // 引入样式
import { useListComponent } from '../pageTs'; // 引入逻辑
const { dataInfo, options } = useListComponent();
const { proxy } = getCurrentInstance() as any;
const data: any = reactive({
  loading: false,
  loadingMsg: '',
  mainPage: 1,
  form: {
    workTaskNo: "", // 工艺作业任务单号（唯一识别码）
    craftTaskNo: "", // 生产工艺任务单号（唯一识别码）
    produceTaskBillNo: "", // 生产任务单号（唯一识别码）
    saleOrderNo: "", // 销售订单号（关联销售订单表 SaleOrder.SaleOrderCode）
    workPerson: "", // 作业人员（创建人员）
    workBeginTime: "2025-05-17T08:30:00", // 作业任务开始时间
    workFinishTime: "2025-05-17T17:00:00", // 作业任务完成时间
    workTaskRemark: "", // 作业备注
    craftWorkState: 1, // 工艺作业任务状态：0作业中；1已完成；2已停工；3挂起
    useEquipment: "", // 使用的机台设备编码(MachineEquipment.EquipmentCode)
    produceMeters: 1000.0, // 总米数(枚数)
    defectiveProductsMeters: 50.0, // 不良品米数(枚数)
    otherDefectiveRate: 0.05, // 不良率
    knifeVersionHieght: 10.5, // 模切-刀版高度
    cropCount: 100, // 模切-刀次
    hopDistance: 50.0, // 模切-每切跳距
    perGroupCount: 50, // 检验-每组枚数
    perGroupHeight: 20.0, // 检验-每组高度
    skipDistance: 100.0, // 检验-跳距
    taskUseTime: 480, // 任务总耗时，单位：分钟
    actualWorkTime: 420, // 实动工时（生产工时），单位：分钟
    dinnertime: 60, // 吃饭时间
    equipmentName: "", // 设备名称
    craftTaskName: "", // 工艺名称
    machineName: "", // 机台名称
    machineType: "", // 机台类型编码
    workPersonName: "", // 作业人员名称（创建人员）
    machineTypeName: "", // 机台类型编码
    produceCraftWorkTaskFragments: [
      {
        produceCraftWorkTaskFragmentCode: "", // 唯一Code
        craftTaskNo: "", // 生产工艺任务编码
        workTaskNo: "", // 生产工艺任务作业编码
        workPerson: "", // 操作人编码
        fragmentBeginTime: "", // 片段开始时间
        fragmentEndTime: "", // 片段结束时间
        fragmentEndType: null, // 片段结束方式：0-暂停、1-分批、2-完成
        fragmentEndReason: null, // 片段结束原因：0-作业、1-调机、2-开会、3-其它
        fragmentEndRemark: "", // 片段结束备注
        isEnded: true // 是否结束
      }
    ]
  },
  productOrder: {},//产品信息
});
const isEdit = ref(true)

import { useRoute } from 'vue-router';
// 获取当前路由对象
const route = useRoute();
//获取生产米数
const getWorkState = (row: any) => {
  if (!!!row.craftWorkState && row.craftWorkState !== 0) return
  console.log(row.craftWorkState);
  switch (row.craftWorkState) {
    case 0: //作业中
      const _list = row.produceCraftWorkTaskFragments
      const _lastRow = _list[_list.length - 1]
      _lastRow.fragmentEndTime = ''
      break;

  }
}
//获取生产米数
const actualWorkTime = (row: any) => {
  if (!row.taskUseTime || !row.dinnertime) return
  const _actualWorkTime = (row.taskUseTime - row.dinnertime).toFixed(0);
  row.actualWorkTime = _actualWorkTime
  return _actualWorkTime
}
//获取生产米数
const changeProduceMeters = (row: any) => {
  if (!row.cropCount) return
  if (row.machineTypeName === '检验') {
    if (!row.perGroupCount || !row.perGroupHeight) return
    row.produceMeters = proxy.$count(`(${row.cropCount || 0}/${row.perGroupCount || 1})*${row.perGroupHeight || 0}`)
  } else if (row.machineTypeName === '模切') {
    if (!row.perGroupHeight) return
    row.produceMeters = proxy.$count(`${row.cropCount || 0}*${row.perGroupHeight || 0}`)
  }
}
//获取不良率
const otherDefectiveRate = (row: any) => {
  if (!row.produceMeters || !row.defectiveProductsMeters) return 0
  const _otherDefectiveRate: string = (
    (row.defectiveProductsMeters / row.produceMeters) * 100
  ).toFixed(2);
  row.otherDefectiveRate = Number(_otherDefectiveRate)
  return Number(_otherDefectiveRate)
}
//获取数据
const getForm = () => {
  let _query: any = route.query
  //获取工单信息
  setLoading()
  if (!!_query.produceTaskBillNo) {
    proxy.$api.ProductionBusniess.GetProduceTaskBillDetail({
      produceTaskBillNo: _query.produceTaskBillNo
    })
      .then((res: any) => {
        data.productOrder = res
        data.loading = false
      })
      .catch(() => {
      });
  }
  if (!!!_query.workTaskNo) {
    data.loading = false
    return
  }
  proxy.$api.ProductionBusniess.GetProduceCraftWorkTaskDetailByCode({
    workTaskNo: _query.workTaskNo,
  })
    .then((res: any) => {
      proxy.$message('获取成功')
      isEdit.value = (['1', '2'].includes(_query.type))
      data.form = res
      data.loading = false
      proxy.$api.ProductionBusniess.GetReportWorkOrderByNo({
        reportWorkOrderNo: res.craftTaskNo,//生产任务单号（唯一识别码）
      })
        .then((res: any) => {
          data.form.wordList = res?.details || []
        })
        .catch(() => {
        });
    })
    .catch(() => {
      data.loading = false
    });
};
const saveBtn = (form: any, isConfirm: boolean = false) => {
  const _form: any = {
    workTaskNo: form.workTaskNo,//	工艺作业唯一编码
    craftWorkState: form.craftWorkState,//	新版看板使用字段-工艺作业任务状态：0作业中；1已完成；2已停工；3挂起
    produceMeters: form.produceMeters,//	生产米数，单位：米
    defectiveProductsMeters: form.defectiveProductsMeters,//不良品米数
    workTaskRemark: form.workTaskRemark,//作业备注
    knifeVersionHieght: form.knifeVersionHieght,//刀版高度-模切专用
    hopDistance: form.hopDistance,//每切跳距-模切专用
    cropCount: form.cropCount,//刀次-模切专用
    perGroupCount: form.perGroupCount,//每组枚数-检验专用
    perGroupHeight: form.perGroupHeight,//每组高度-检验专用
    skipDistance: form.skipDistance,//跳距-检验专用
    produceCraftWorkTaskFragments: form.produceCraftWorkTaskFragments.map((el: any) => ({
      produceCraftWorkTaskFragmentCode: el.produceCraftWorkTaskFragmentCode,//时间片段唯一code
      fragmentBeginTime: el.fragmentBeginTime,//片段开始时间
      fragmentEndTime: el.fragmentEndTime,//片段结束时间
      fragmentEndType: el.fragmentEndType,//片段结束方式：0-暂停、1-分批、2-完成	
      fragmentEndReason: el.fragmentEndReason,//片段结束原因：0-作业、1-调机、2-开会、3-其它
      fragmentEndRemark: el.fragmentEndRemark,//片段结束备注
    })),//跳距-检验专用
  }
  if (form.workTaskNo) {
    proxy.$api.ProductionBusniess.UpdateProduceCraftWorkTask(_form)
      .then((res: any) => {
        if (isConfirm) {
          _setState(form)
        } else {
          _sun()
        }
      })
      .catch(() => { });
  }
  function _sun() {
    proxy.$message('保存成功')
    sendMsg('save', true);
    // getForm()
    window.close();
  }
  function _setState(form: any) {
    proxy.$messageBox('是否确定完成该数据,完成后不可编辑!', () => {
      proxy.$api.ProductionBusniess.FinishedDataProduceBill(form)
        .then((res: any) => {
          _sun()
        })
        .catch(() => { });
    });
  }
};
const setLoading = (title: string = '正在获取数据,请稍等...') => {
  if (!data.loading) {
    data.loading = true;
    data.loadingMsg = title;
  }
};
onMounted(() => {
  getForm();
});
</script>
